package app.base.systemmainframe;

import java.io.IOException; 
import java.io.PrintWriter; 

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//import javax.servlet.http.HttpSession;

import app.base.common.FileOperation;
import app.base.common.UserSessionInfo;
import app.base.common.Utility;

import app.base.systemmanage.systemusersmanage.dao.SysUsersDAO;

public class UserLoginHandle extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	private String webappServletContextRealpath = null;
	
	private final static String APP_SYS_PROGRAM_LOOKUP_ROOT_PATH_REPLACEMENT = "\\{@WEBAPP_ROOT_PATH\\}";
	private final static String APP_SYS_PROGRAM_LOOKUP_ROOT_PATH = "";
	
	static {

	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 
		
		if (webappServletContextRealpath == null)
		{
			webappServletContextRealpath = this.getServletConfig().getServletContext().getRealPath("/");
			//webappContextRealpath = request.getContextPath() + "/";			
		}
		
		String cmd = request.getParameter("SYS_OP_CMD");

		if (cmd == null || cmd.trim().length() == 0)
		{
		    response.setHeader("User-Defined-Session-Status","login/reset/timeout");     

			out.println(getDefaultHtmlPage().toString());			
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_LOGIN_VERIFY))
		{
		    Map<String, Object> map = new HashMap<String, Object>();
		    
			String loginId = request.getParameter("userId");
			String loginPwd = request.getParameter("userPwd");
		    
			if (loginId == null || loginPwd == null)
			{
				out.println("{success: true, msg: {ReturnCode: '-1', Description: '用户登录失败：用户账户/密码不能为空'}}");
			}
			else
			{
				map.put("loginId", loginId);
				try {
					map.put("loginPwd", Utility.MD5(loginPwd).toUpperCase());
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				int ret = login(request, map);
				
				if (ret == 1)
				{		
					out.println("{success: true, msg: {ReturnCode: '0', Description: '用户登录成功：用户登录成功'}}");					
				}
				else if (ret == 0)
				{
					out.println("{success: true, msg: {ReturnCode: '-1', Description: '用户登录失败：用户账号或者密码输入错误'}}");						
				}
				else
				{
					out.println("{success: true, msg: {ReturnCode: '-1', Description: '系统错误：系统发生未知错误'}}");						
				}				
			}
		}
		else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_LOGIN_OUT))
		{
			logout(request);
			out.println("{success: true, msg: {ReturnCode: '0', Description: '用户退出系统成功'}}");
		}
		
		out.flush();
		out.close();
	} 
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
		doGet(request, response);
	} 
	
	@SuppressWarnings("unchecked")
	private int login(HttpServletRequest request, Map<String, Object>  map)
	{
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysUsersDAO sysUsersDAO = (SysUsersDAO)context.getBean(Utility.SYSTEM_USERS_MANAGE_MODULE_BEAN_NAME);
		
		int count = sysUsersDAO.count_0002(map);
		
		if (count == 1)
		{
			List list = sysUsersDAO.select_0002(map);	
			
			String userId = ((Map) list.get(0)).get("USER_ID").toString().trim();
			
			UserSessionInfo usi = new UserSessionInfo();
			
			usi.setLoginId((String) map.get("loginId"));
			usi.setUserId(userId);
			
			//usi.setUserRoles(UserSessionInfo.getUserRoles(userId));
			usi.setUserPerms(UserSessionInfo.getUserPerms(userId));
						
			request.getSession().setAttribute(Utility.LOGIN_USER_SESSION_INFO, usi);
		}

		return count;
	}
	
	private int logout(HttpServletRequest request)
	{
		request.getSession().invalidate();
		return 0;
	}

	private StringBuffer getDefaultHtmlPage()
	{
		StringBuffer pageContent = new StringBuffer();

		pageContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
		pageContent.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">\n");
		pageContent.append("<head>\n");
		pageContent.append("<title>" + Utility.SYSTEM_LOGO_TITLE + " -- 用户登录</title>\n\n");
		pageContent.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
		pageContent.append("<meta content=\"JAVA\" name=\"CODE_LANGUAGE\">\n");
		pageContent.append("<meta content=\"JavaScript\" name=\"DEFAULTCLIENTSCRIPT_LANGUAGE\">\n\n");

		try {
			FileOperation fo = new FileOperation(webappServletContextRealpath + Utility.APP_SYS_USER_LOGIN_INCLUDE_PATH);
						
			Pattern pattern = Pattern.compile(APP_SYS_PROGRAM_LOOKUP_ROOT_PATH_REPLACEMENT);
			Matcher matcher = pattern.matcher(fo.readfrom(Utility.CHARSET_ENCODING_UTF8).toString());
			
			pageContent.append(matcher.replaceAll(APP_SYS_PROGRAM_LOOKUP_ROOT_PATH));			
		}
		catch (Exception e)
		{
			pageContent.append(e.toString());
		}
		
		pageContent.append("\n</head>\n");
		pageContent.append("<body>\n");
		pageContent.append("</body>\n");
		pageContent.append("</html>");
		
		return pageContent;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
	}

}